﻿/*
 * Copyright 2009 - 2010 eScience Institute
 *
 * This file is part of SqlShare.
 *
 * SqlShare is free software: you can redistribute it and/or modify it under the terms 
 * of the GNU General Public License as published by the Free Software Foundation, 
 * either version 3 of the License, or (at your option) any later version.
 *
 * SqlShare is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with 
 * SqlShare. If not, see http://www.gnu.org/licenses/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Security.Cryptography;
using System.Xml;
using System.Text;
using Microsoft.WindowsAzure.ServiceRuntime;
using SqlShareAPI;

namespace WebQueryRole
{
    public partial class Login : System.Web.UI.Page
    {        
        protected SSAPIFactory _factory;
        protected bool _justLoggedIn;
        protected bool _loggedIn;

        protected override void OnInit(EventArgs e)
        {
            _factory = CloudUtil.CreateSSAPIFactory();
            base.OnInit(e);
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);
            _factory.Close();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            UserSession userSession = WebAuthentication.IsLoggedIn(this, _factory);
            string url = Request["url"];
            string other = hiddenInputURL.Value;

            // login as temp user
            if (userSession == null && !RoleEnvironment.IsAvailable)
            {
               userSession = AttemptLogin("test", "test123");
            }

            if (!String.IsNullOrEmpty(Request["url"]))
            {
                hiddenInputURL.Value = Request["url"];
            }

            // check action
            string action = Request["action"];
            if (!string.IsNullOrEmpty(action))
            {
                if (action == "logout" && userSession != null && Request["token"] == userSession.Token)
                {
                    WebAuthentication.LogOut(this, userSession);
                    userSession = null; // reset it so rest of form can complete properly
                }
            }

            // if we got to this page with post data..
            string submitType = Request.Form["submit"];            

            if (userSession != null)
            {
                informationDiv.InnerText = "You are logged in as: " + userSession.UserName;
            }
            else if (!String.IsNullOrEmpty(submitType) && submitType.Equals("login"))
            {
                userSession = AttemptLogin(Request.Form["username"], Request.Form["password"]);                
                if(userSession == null)
                {
                    // login failure update message text and stay on the same page
                    informationDiv.InnerHtml = "<span style=\"color:red\"> Invalid Credentials. </span>";
                }                
            }
            _loggedIn = userSession != null;
        }

        private UserSession AttemptLogin(string username, string password)
        {
            UserSession userSession = WebAuthentication.LogIn(this, username, password, _factory);
            if (userSession != null)
            {
                string url = String.IsNullOrEmpty(Request["url"])? "/" : Request["url"];                
                        
                Response.BufferOutput = true;
                Response.Redirect(url);

                _justLoggedIn = true;
            }
            return userSession;
        }    

    }
}
